<template>
  <eui-background type="common">
    <view class="content-img">
      <eui-nav-bar title="缺货拣货" color="#fff" />
      <view class="footer" :style="{ height: height + 'px' }" v-if="goodsList.length > 0">
        <view
          style="width: 100%;background: #FFE9DA;padding: 15rpx 20rpx 15rpx 15rpx;color:#FF0000;box-sizing: border-box;font-size: 32rpx;line-height: 35rpx;"
          class="flex just-between align-center">
          <view style="flex: 1;">提示：选择“按金额”时，请直接输入退款金额，若同一商品存在，则“退差金额”为多件商品的退差金额</view>
          <view
            style="padding:6rpx 10rpx;height: 35rpx;border-radius: 3rpx;border: 1rpx solid #FF0000;text-align: center;line-height: 35rpx;margin-left: 22rpx;"
            @click="openContactCustPop">
            联系顾客</view>
        </view>
        <view
          style="height: 68rpx;font-size: 32rpx;line-height: 35rpx;padding: 17rpx 17rpx 10rpx 10rpx;box-sizing: border-box;"
          class="flex align-center just-between">
          <view>请选择需要退差的商品</view>
          <view
            style="width: 120rpx; height: 40rpx; background: linear-gradient( 156deg, #4FE0EA 0%, #85B6FD 100%); border-radius: 20rpx;"
            class="flex align-center just-between" v-show="refundType == '1'" @click="changeType">
            <view style="width: 35rpx;height: 35rpx;background-color: #fff;margin:2rpx;border-radius: 35rpx;">
            </view>
            <view style="flex:1;font-size: 22rpx;color: #fff;text-align: right;margin-right: 12rpx;">按金额
            </view>
          </view>
          <view
            style="width: 120rpx; height: 40rpx; background: linear-gradient( 156deg, #BDBDBD 0%, #808489 100%); border-radius: 20rpx;"
            class="flex align-center just-between" v-show="refundType == '2'" @click="changeType">
            <view style="flex:1;font-size: 22rpx;color: #fff;text-align: le f t;margin-left: 12rpx;">按重量
            </view>
            <view style="width: 35rpx;height: 35rpx;background-color: #fff;margin:2rpx;border-radius: 35rpx;">
            </view>
          </view>
        </view>
        <view class="bg-white" style="width: 100%;padding: 10rpx 18rpx;box-sizing: border-box;">
          <view>
            <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
              <checkbox-group @change="checkboxChange(index)">
                <checkbox :value="item.orderGoodsId" :checked="item.checked" />
              </checkbox-group>
              <view
                style="width: 40rpx;height: 40rpx;text-align: center;line-height: 40rpx;background-color: #D8D8D8;color: #fff;border-radius: 40rpx;font-size: 32rpx;margin-top: 13rpx;">
                {{ index + 1 }}
              </view>
              <view style="margin-left: 17rpx;box-sizing: border-box;flex: 1">
                <view class="goods-info just-between">
                  <view style="">
                    <view class="goods-name bold">{{ item.goodsName }}</view>
                    <view style="font-size: 32rpx;color: #626262;">
                      {{ item.goodsCode }}-{{ item.goodsBarcode }}
                    </view>
                  </view>
                  <view style="color: #626262;text-align: right;">
                    <view style="font-weight: bold;" class="goods-quantity">¥ {{ item.goodPrice }}</view>
                    <view class="goods-quantity">
                      可退数量<text style="font-weight: bold;color: #000;margin-left: 4rpx;">{{ item.partRefundGoodsNum
                        }}</text></view>
                  </view>
                </view>
                <view
                  style="display: flex;justify-content: space-between;margin-top: 6rpx;height: 48rpx;font-size: 32rpx;margin-bottom: 10rpx;"
                  v-show="item.checked && refundType == '1'">
                  <view class="flex align-center co-00" style="height: 48rpx;">
                    <view
                      style="width: 72rpx; height: 32rpx; background: #D4F2FF; border-radius: 3rpx;text-align: center;line-height: 28rpx;color: #4B9BFF;font-size: 32rpx;margin-right: 6rpx;">
                      退差</view>
                    <view class="goods-price co-00">
                      可退金额 <text style="font-weight: bold;margin-left: 6rpx;"> ¥ {{ item.totalPrice }}</text>
                    </view>
                  </view>
                  <view style="font-size: 32rpx;" class="flex align-center co-00">
                    <view>退差金额</view>
                    <view
                      style="width: 163rpx;height: 47rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                      class="flex">
                      <text>¥</text>
                      <input placeholder="请输入" placeholder-style="color:#959595;font-size: 32rpx;" type="number"
                        v-model="item.applyRefundPrice" @input="handleInput(index)"
                        style="padding: 2rpx 0 2rpx 2rpx;" />
                    </view>
                  </view>
                </view>
                <view v-show="item.checked && refundType == '2'" style="margin-bottom: 10rpx;">
                  <view
                    style="display: flex;justify-content: space-between;margin-top: 6rpx;height: 48rpx;font-size: 32rpx;color: #000;">
                    <view class="flex align-center co-00">
                      <view
                        style="width: 72rpx; height: 28rpx; background: #D4F2FF; border-radius: 3rpx;text-align: center;line-height: 28rpx;color: #4B9BFF;font-size: 32rpx;margin-right: 6rpx;">
                        退差</view>
                      <view class="goods-price co-00">
                        应拣重量 <text style="font-weight: bold;margin-left: 6rpx;">{{ item.refundsGoodsWeight }}g</text>
                      </view>
                    </view>
                    <view style="font-size: 32rpx;" class="flex align-center">
                      <view>实拣重量</view>
                      <view
                        style="width: 163rpx;height: 47rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                        class="flex">
                        <input placeholder="请输入" placeholder-style="color:#959595;font-size: 32rpx;" type="number"
                          v-model="item.applyRefundWeight" @input="handleInputWeight($event, index, 'input')"
                          style="padding: 2rpx 0 2rpx 2rpx;" @blur="handleInputWeight($event, index, 'blur')" />
                        <text class="bold">g</text>
                      </view>
                    </view>
                  </view>
                  <view
                    style="display: flex;justify-content: space-between;margin-top: 6rpx;height: 48rpx;font-size: 32rpx;color: #000;margin-left: 78rpx;">
                    <view class="flex align-center">
                      <view class="goods-price">
                        可退金额 <text style="font-weight: bold;margin-left: 6rpx;">¥ {{ item.totalPrice
                          }}</text>
                      </view>
                    </view>
                    <view style="font-size: 32rpx;" class="flex align-center">
                      <view>退差金额</view>
                      <view
                        style="width: 163rpx;height: 47rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                        class="flex">
                        <text>¥</text>
                        <input placeholder="请输入" placeholder-style="color:#959595;font-size: 32rpx;" type="number"
                          v-model="item.applyRefundPrice" @input="handleInput(index)"
                          style="padding: 2rpx 0 2rpx 2rpx;" />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view style="padding: 20rpx 0;">
              <view style="font-size: 32rpx;" class="flex just-between bold">
                <view>退差件数</view>
                <view>{{ sumNum() }}</view>
              </view>
              <view style="font-size: 32rpx;margin-top: 6rpx" class="flex just-between bold">
                <view>合计退款</view>
                <view style="color: #E43E00;">¥{{ sum() }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="footer align-center" :style="{ height: height + 'px' }" v-else>
        <view class="m-list-template-image" style="flex: 1;margin-top: 25%;">
          <image :src="_img_blank_order" />
          <view style="color: #9e9e9e;font-size: 32rpx;text-align: center;">无可退商品</view>
        </view>
      </view>
      <eui-button v-if="goodsList.length > 0" title="下一步" type="min" singleTag="confirm" @buttonClick="buttonClick"
        style="width: 100%;height: 86rpx;line-height: 86rpx;margin: 0;border-radius: 0;"
        :disabled="sum() == 0"></eui-button>
    </view>
    <template>
      <view>
        <eui-popup ref="popup" background-color="#fff" type="bottom" :mask-click="false">
          <view class="popup-content">
            <view class="popup-title flex just-between">
              <view style="font-weight: bold;">
                选择退款理由
              </view>
              <bcm-close-btn @click="close"></bcm-close-btn>
            </view>
            <scroll-view scroll-y="true"
              style="padding: 8rpx 8rpx 8rpx 30rpx;box-sizing: border-box;height: 70vh;overflow-y: scroll;text-align: left;">
              <radio-group @change="selectItem">
                <view v-for="item in getBcmDictList('orderCancelReasonType')" :key="item.value">
                  <radio :value="item.value" :checked="orderCancelReasonType === item.value"
                    style="margin-top: 20rpx;line-height: 35rpx">
                    {{ item.text }}
                  </radio>
                </view>
              </radio-group>
              <textarea v-model="rejectReason" placeholder="请输入原因" v-if="orderCancelReasonType == '999'"></textarea>
            </scroll-view>
            <view class="bottom-1">
              <eui-button type="min" title="提交" style="width: 50%;" singleTag="sure" @buttonClick="buttonClick" />
            </view>
          </view>
        </eui-popup>
        <eui-popup ref="contactCustPopup" type="bottom" :animation="false" background-color="#fff" :mask-click="false">
          <view class="popup-content">
            <view class="popup-title flex just-between">
              <view style="font-weight: bold;">
                联系顾客
              </view>
              <bcm-close-btn @click="closeContactCustPopup"></bcm-close-btn>
            </view>
            <view
              style="padding-left: 30rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;">
              <view>
                <text v-if="consigneeName">姓名：{{ consigneeName }}</text><text v-if="consigneePhoneLast">(尾号{{
        consigneePhoneLast }})</text>
              </view>
              <view>
                <text v-if="consigneePhone">电话：{{ consigneePhone }}</text>
              </view>
              <view class="bottom-1" style="margin: 100rpx 0 50rpx 0;">
                <eui-button type="min" title="拨打电话" style="width: 50%" singleTag="submit" @buttonClick="buttonClick" />
              </view>
            </view>
          </view>
        </eui-popup>
      </view>
    </template>
  </eui-background>
</template>
<script setup>
import { mapState, mapMutations } from 'vuex';
import { ref, computed, onMounted } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, makePhoneCall, formatPrice } from '../../../hooks/bcmUseUntils';
import _img_blank_order from '../../../static/img/status/blank_order.png'
const bcmUrl = getBcmUrl();

const goodsList = ref([])
const refundType = ref('1')
const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderId = ref('')
const consigneeName = ref('')
const consigneePhone = ref('')
const consigneePhoneLast = ref('')
const chnlType = ref('')
const orderStatus = ref('')
const height = ref(0)
const contactCustPopup = ref(null);
const popup = ref(null)
const showConfigModal = ref(false)

onMounted(() => {
  uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".navigation");
      info.boundingClientRect(function (data) { //data - 各种参数
        height.value = res.windowHeight - data.height - 100;
      }).exec()
    }
  });
})

onLoad((option) => {
  let options = service.getStorageSync('partOptions');
  goodsList.value = options.goodsList;
  orderId.value = options.orderId;
  consigneeName.value = options.consigneeName;
  consigneePhone.value = options.consigneePhone;
  consigneePhoneLast.value = options.consigneePhoneLast;
  chnlType.value = options.chnlType;
  orderStatus.value = option.orderStatus;
  showConfigModal.value = option.showModal || false;
})

const selectItem = (e) => {
  orderCancelReasonType.value = e.detail.value;
}

const checkboxChange = (index) => {
  let list = [...goodsList.value]
  const item = list[index];
  // $set(item, 'checked', !item.checked)
  item.checked = !item.checked;
  goodsList.value = list;
}

const handleInput = (index) => {
  let list = [...goodsList.value]
  const item = list[index];
  if (item.applyRefundPrice < 0) {
    uni.showToast({
      title: '输入值不能小于0',
      icon: 'none'
    });
    item.applyRefundPrice = 0.00;
  } else if (item.applyRefundPrice - item.totalPrice > 0) {
    uni.showToast({
      title: '输入值不能超过' + item.totalPrice,
      icon: 'none'
    });
    item.applyRefundPrice = item.totalPrice;
  }
  goodsList.value = list;
}
const handleInputWeight = (event, index, type) => {
  let list = [...goodsList.value]
  const item = list[index];
  // item.applyRefundWeight = event.target.value;
  if (Number(item.applyRefundWeight) < 0) {
    uni.showToast({
      title: '输入值不能小于0',
      icon: 'none'
    });
    item.applyRefundWeight = 0;
  } else if (item.applyRefundWeight - item.refundsGoodsWeight > 0) {
    uni.showToast({
      title: '输入值不能超过' + item.refundsGoodsWeight,
      icon: 'none'
    });
    item.applyRefundWeight = item.refundsGoodsWeight;
  }
  if (type == 'blur') {
    if (!!item.applyRefundWeight || item.applyRefundWeight == 0) {
      let pricePerg = (item.totalPrice / item.refundsGoodsWeight);
      item.applyRefundPrice = ((item.refundsGoodsWeight - item.applyRefundWeight) * pricePerg).toFixed(2);
      goodsList.value = list;
    }
  }
}
const sumNum = () => {
  return goodsList.value.filter(a => !!a.checked).reduce((accumulator, currentValue) => {
    return accumulator + currentValue.partRefundGoodsNum;
  }, 0)
}
const sum = () => {
  let sum = goodsList.value.filter(a => !!a.checked).reduce((accumulator, currentValue) => {
    let num = Number(currentValue.applyRefundPrice);
    if (!isNaN(num)) {
      return accumulator + num;
    } else {
      return accumulator;
    }
  }, 0)
  return sum.toFixed(2)
}
const changeType = () => {
  refundType.value = refundType.value == '1' ? '2' : '1';
  goodsList.value.map(v => {
    if (refundType.value == '1') {
      v.applyRefundWeight = null;
      v.applyRefundPrice = null;
    } else {
      v.applyRefundPrice = null;
    }
  })
}
const buttonClick = async (t, v) => {
  let list = goodsList.value.filter(a => !!a.checked);
  switch (t) {
    case 'sure':
      if (!orderCancelReasonType) {
        uni.showToast({
          title: '请选择退款理由',
          icon: 'none'
        });
        return;
      }
      if (orderCancelReasonType.value == '999' && !rejectReason.value) {
        uni.showToast({
          title: '请输入退款原因',
          icon: 'none'
        });
        return;
      }
      service.enjoyShowLoading('正在处理...');
      let params = {
        orderId: orderId,
        reasonType: orderCancelReasonType.value,
        reasonDesc: orderCancelReasonType.value != '999' ? getBcmDictName('orderCancelReasonType', orderCancelReasonType.value) : rejectReason.value,
        refundGoodsDetailList: list.map(v => {
          return {
            orderGoodsId: v.orderGoodsId,
            refundGoodsAmount: v.applyRefundPrice,
            prePartReturnInfo: v.prePartReturnInfo
          }
        })
      }
      let response = await bcmRequest(bcmUrl.orderApi, '订单表', 'orderPriceRefundDiff', params);
      service.enjoyHideLoading();
      popup.value.close('bottom');
      uni.showToast({
        title: '退款成功',
        icon: 'none'
      });
      if (response?.afsOrderId && (!['2', '1'].includes(response?.syncErpBreakageStatus)) && orderStatus.value == '4' && showConfigModal) {
        uni.navigateTo({
          url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + response?.afsOrderId+'&type=1'
        });
      } else {
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
          uni.$emit('REFRESH_ORDER_DETAIL_DATA');
          uni.$emit('REFRESH_ORDER_SEARCH_DATA')
        }, 1000)
      }
      break;
    case 'confirm':
      if (list.length == 0) {
        uni.showToast({
          title: '请选择需要退差的商品',
          icon: 'none'
        });
        return;
      }
      let sum = sum();
      if (sum == 0) {
        uni.showToast({
          title: '请输入退差金额',
          icon: 'none'
        });
        return;
      }
      popup.value.open('bottom');
      break;
    case 'submit':
      // #ifdef APP-PLUS
      makePhoneCall(consigneePhone.value)
      // plus.device.dial(consigneePhone.value, true);
      // #endif
      break;
  }
}
const close = function () {
  popup.value.close();
  orderCancelReasonType.value = '';
  rejectReason.value = '';
}
const openContactCustPop = function () {
  contactCustPopup.value.open('bottom');
}
const closeContactCustPopup = () => {
  contactCustPopup.value.close();
}

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

uni-checkbox {
  ::v-deep .uni-checkbox-input {
    transform: scale(.6);
  }
}

.content {
  // background-color: $uni-background;
  padding: 0;
}

.navigation {
  flex: 0 0 auto;
}

.content-img {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  // background: $uni-background-img;
  background-size: 100% 150px;
}

.footer {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: #f5f7fa;
}

.bottom {
  display: flow-root;
  height: 76rpx;
  text-align: center;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: $uni-bg-color;
}

//list
.goods-item {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #e1e1e1;
}

.goods-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.m-list-template-image {
  width: 100%;
  margin: auto 0;
  text-align: center;
}

.goods-name {
  margin-bottom: 2px;
  font-size: 32rpx;
  line-height: 35rpx;
}

.goods-price {
  font-size: 28rpx;
  text-align: right;
}

.goods-quantity {
  font-size: 28rpx;
}

.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>
